using FirstDemo.Common;
using FirstDemo.Models;
using Hangfire;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Postal;
using Postal.AspNetCore;
using StackExchange.Redis;
using System;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace FirstDemo.Controllers
{
    [Route("api/[controller]")]
    public class LoginController : Controller
    {
        //邮件使用
        private readonly IEmailService _emailService;
        private readonly EmailServiceOptions _emailServiceOptions;

        private readonly IDatabase _redis;
        MySQLHelper _helper = new MySQLHelper(GlobalString.MySQLString);
        //private JwtConfig jwtconfig;
        public LoginController(RedisHelper redis, IEmailService emailService,
            IOptions<EmailServiceOptions> o)     //通过构造函数获取注入的依赖
        {
            _redis = redis.GetDatabase();
            _emailService = emailService;
            _emailServiceOptions = o.Value;
        }

        /// <summary>
        /// 用户登录API
        /// </summary>
        /// <param name="userName">用户名称</param>
        /// <param name="pwd">密码</param>
        /// <returns>登录成功返回Token，登录失败返回false</returns>
        [HttpGet]
        public async Task<JsonResult> Get(string userName, string pwd)
        {
            GlobalString.UserName = userName;
            var isOK = _helper.ExecSqlScalar($"select * from User where UserName = '{userName}' and Pwd = '{pwd}'");
            if (isOK != null)
            {
                string token = Utils.GetToken(userName, "1");
                HttpContext.Items.Add("Message", "用户登录成功");
                HttpContext.Session.SetString("Token", token);
                _redis.StringSet("UserName", userName);
                _redis.StringSet("Pwd", pwd);

                //通过定时任务来调用邮件发送
                RecurringJob.AddOrUpdate("myRecurringJob", () => Console.WriteLine("Recurring!"), "0 * * * * ? *");
                //BackgroundJob.Schedule(() => NotifyNewLoginAsync(1), TimeSpan.FromMinutes(2));

                return Json(new ResultModel(Response.StatusCode, token));
            }
            else
            {
                HttpContext.Items.Add("Message", "用户登录失败");
                return Json(new ResultModel(Response.StatusCode, false));
            }

        }

        /// <summary>
        /// 通过Session获得其中的Token值，通过Redis获得用户名及密码
        /// </summary>
        /// <returns>Token的值</returns>
        [Authorize]
        [HttpGet("token")]
        public JsonResult GetToken()
        {
            return Json("Token: " + HttpContext.Session.GetString("Token") +
                    "UserName: " + _redis.StringGet("UserName") +
                    "Pwd: " + _redis.StringGet("Pwd")
                );
        }

        /// <summary>
        /// 通过邮件通知
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        [HttpGet("Notify")]
        [AutomaticRetry(Attempts = 20)] //当邮件Send方法抛出异常时，Hangfire将在延迟后自动重试
        public async Task NotifyNewLoginAsync(int UserId)
        {
            string username = "Lesan"; //可以通过Id从数据库查
            string mail = "1960681385@qq.com";

            var emailData = new Email("Testing1");
            emailData.ViewData["to"] = "1960681385@qq.com";
            emailData.ViewData["Name"] = "Lesan";
            await _emailService.SendAsync(emailData);
        }
    }
}
